package org.example.blog.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.blog.pojo.Result;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {
    //上传图片
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        //file效验
        if(file.isEmpty()){
            return "图片上传失败";
        }
        //file 图片重命名
        String originalFilename = file.getOriginalFilename();
        String ext = "." + originalFilename.split("\\.")[1];
        String uuid = UUID.randomUUID().toString().replace("-","");
        String fileName = uuid + ext;
        //上传图片
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                "\\src\\main\\resources\\static\\images\\";
        String p = "http://localhost:8888/img/";
        String path = pre + fileName;
        try {
            file.transferTo(new File(path));
            return p + fileName;
        } catch (IOException e){
            e.printStackTrace();
        }
        return "图片上传失败";
    }
}
